<template>
  <div class="word-forum" :class="theme">
    <div class="admin-container">
      <!-- 顶部导航栏 -->
      <header class="admin-header">
        <div class="header-left">
          <h1>文章管理</h1>
        </div>
        <div class="header-right">
          <button class="theme-toggle" @click="toggleTheme">
            <span v-if="theme === 'light'">🌙</span>
            <span v-else>☀️</span>
          </button>
          <span class="admin-name">管理员</span>
        </div>
      </header>

      <!-- 主要内容区 -->
      <div class="admin-content">
        <!-- 搜索和筛选区域 -->
        <div class="toolbar">
          <div class="search-box">
            <input type="text" v-model="searchQuery" placeholder="搜索文章标题或关键词..." @input="applyFilters" />
            <button class="search-btn">
              <svg viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor"
                  d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 0 0 1.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 0 0-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 0 0 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" />
              </svg>
            </button>
          </div>

          <div class="filters">
            <select v-model="filterCategory" @change="applyFilters">
              <option value="">所有分类</option>
              <option v-for="cat in categories" :key="cat" :value="cat">
                {{ cat }}
              </option>
            </select>

            <select v-model="sortField" @change="applyFilters">
              <option value="date">按时间排序</option>
              <option value="votes">按点赞数排序</option>
              <option value="comments">按评论数排序</option>
            </select>

            <select v-model="sortOrder" @change="applyFilters">
              <option value="DESC">降序</option>
              <option value="ASC">升序</option>
            </select>
          </div>

          <button class="refresh-btn" @click="resetFilters">
            <svg viewBox="0 0 24 24" width="18" height="18">
              <path fill="currentColor"
                d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
            </svg>
            重置
          </button>
        </div>

        <!-- 文章表格 -->
        <div class="table-container">
          <table class="articles-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>标题</th>
                <th>关键词</th>
                <th>分类</th>
                <th>点赞</th>
                <th>评论</th>
                <th>日期</th>
                <th>作者ID</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="article in paginatedArticles" :key="article.id">
                <td>{{ article.id }}</td>
                <td class="title-cell">
                  <span class="title-text">{{ article.title }}</span>
                </td>
                <td>{{ article.word }}</td>
                <td>
                  <span class="category-badge" :style="{ backgroundColor: getCategoryColor(article.category) }">
                    {{ article.category }}
                  </span>
                </td>
                <td>{{ article.votes }}</td>
                <td>{{ article.comments }}</td>
                <td>{{ formatDate(article.date) }}</td>
                <td>{{ article.user_id }}</td>
                <td class="actions">
                  <button class="view-btn" @click="viewArticle(article.id)">
                    <svg viewBox="0 0 24 24" width="16" height="16">
                      <path fill="currentColor"
                        d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z" />
                    </svg>
                  </button>
                  <!-- <button class="edit-btn" @click="editArticle(article.id)">
                    <svg viewBox="0 0 24 24" width="16" height="16">
                      <path fill="currentColor"
                        d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" />
                    </svg>
                  </button> -->
                  <button class="delete-btn" @click="confirmDelete(article)">
                    <svg viewBox="0 0 24 24" width="16" height="16">
                      <path fill="currentColor"
                        d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />
                    </svg>
                  </button>
                </td>
              </tr>
              <tr v-if="filteredArticles.length === 0">
                <td colspan="9" class="no-data">没有找到匹配的文章</td>
              </tr>
            </tbody>
          </table>

          <!-- 分页控件 -->
          <div class="pagination" v-if="totalPages > 1">
            <button :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
              上一页
            </button>
            <span v-for="page in totalPages" :key="page" @click="changePage(page)"
              :class="{ active: page === currentPage }">
              {{ page }}
            </span>
            <button :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">
              下一页
            </button>
            <span class="page-info">共 {{ filteredArticles.length }} 条，每页 {{ pageSize }} 条</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 文章预览模态框 -->
    <div v-if="showPreview" class="modal-overlay" @click.self="showPreview = false">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ previewArticle.title }}</h2>
          <button class="close-btn" @click="showPreview = false">
            <svg viewBox="0 0 24 24" width="20" height="20">
              <path fill="currentColor"
                d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <div class="article-meta">
            <span class="category-badge" :style="{ backgroundColor: getCategoryColor(previewArticle.category) }">
              {{ previewArticle.category }}
            </span>
            <span class="meta-item">关键词: {{ previewArticle.word }}</span>
            <span class="meta-item">点赞: {{ previewArticle.votes }}</span>
            <span class="meta-item">评论: {{ previewArticle.comments }}</span>
            <span class="meta-item">日期: {{ formatDate(previewArticle.date) }}</span>
            <span class="meta-item">作者ID: {{ previewArticle.user_id }}</span>
          </div>
          <div class="article-excerpt">
            <h4>摘要:</h4>
            <p>{{ previewArticle.excerpt }}</p>
          </div>
          <div class="article-content">
            <h4>内容:</h4>
            <div v-html="previewArticle.content"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="confirm-modal">
        <div class="confirm-header">
          <h3>确认删除</h3>
        </div>
        <div class="confirm-body">
          <p>确定要删除文章 "{{ articleToDelete.title }}" 吗？此操作无法撤销。</p>
        </div>
        <div class="confirm-footer">
          <button class="cancel-btn" @click="showDeleteConfirm = false">
            取消
          </button>
          <button class="confirm-btn" @click="deleteArticle">
            确认删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, inject, onMounted } from 'vue';
import { getForumArticles, deleteArticleApi } from '../../api/GetForum.js'
// 主题功能
const theme = inject("theme", ref('light'));
const toggleTheme = () => {
  theme.value = theme.value === 'light' ? 'dark' : 'light';
};

// 分页设置
const pageSize = ref(5); // 每页5条
const currentPage = ref(1);

// 过滤和排序
const searchQuery = ref('');
const filterCategory = ref('');
const sortField = ref('date');
const sortOrder = ref('DESC');

// 模拟6条测试数据
const mockArticles = [
  {
    id: 1,
    title: "Vue3 Composition API 入门指南",
    word: "Vue",
    excerpt: "学习Vue3的Composition API基础用法...",
    category: "技术",
    votes: 42,
    comments: 15,
    date: new Date('2023-05-15'),
    user_id: 1,
    content: "<h3>Vue3 Composition API</h3><p>详细内容...</p>"
  },
  {
    id: 2,
    title: "如何高效学习编程",
    word: "学习",
    excerpt: "分享一些高效学习编程的方法和技巧...",
    category: "学习",
    votes: 35,
    comments: 8,
    date: new Date('2023-05-10'),
    user_id: 2,
    content: "<h3>学习编程</h3><p>详细内容...</p>"
  },
  {
    id: 3,
    title: "CSS Grid布局完全指南",
    word: "CSS",
    excerpt: "全面介绍CSS Grid布局的使用方法...",
    category: "技术",
    votes: 28,
    comments: 12,
    date: new Date('2023-05-05'),
    user_id: 3,
    content: "<h3>CSS Grid</h3><p>详细内容...</p>"
  },
  {
    id: 4,
    title: "健康饮食的五个原则",
    word: "健康",
    excerpt: "介绍保持健康饮食的基本原则...",
    category: "生活",
    votes: 19,
    comments: 5,
    date: new Date('2023-04-28'),
    user_id: 4,
    content: "<h3>健康饮食</h3><p>详细内容...</p>"
  },
  {
    id: 5,
    title: "React与Vue的比较",
    word: "React",
    excerpt: "对比分析React和Vue框架的异同...",
    category: "技术",
    votes: 31,
    comments: 18,
    date: new Date('2023-04-20'),
    user_id: 1,
    content: "<h3>React vs Vue</h3><p>详细内容...</p>"
  },
  {
    id: 6,
    title: "时间管理的七个技巧",
    word: "效率",
    excerpt: "分享提高工作效率的时间管理方法...",
    category: "其他",
    votes: 23,
    comments: 7,
    date: new Date('2023-04-15'),
    user_id: 2,
    content: "<h3>时间管理</h3><p>详细内容...</p>"
  }
];

const articles = ref([]);
const categories = ref(['cet4', 'cet6', 'ielts', 'toefl', 'gre', 'business']);


// 预览相关
const showPreview = ref(false);
const previewArticle = ref(null);

// 删除相关
const showDeleteConfirm = ref(false);
const articleToDelete = ref(null);

// 计算属性
const filteredArticles = computed(() => {
  let result = [...articles.value];

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(article =>
      article.title.toLowerCase().includes(query) ||
      article.word.toLowerCase().includes(query)
    );
  }

  // 分类过滤
  if (filterCategory.value) {
    result = result.filter(article => article.category === filterCategory.value);
  }

  // 排序
  result.sort((a, b) => {
    const field = sortField.value;
    const order = sortOrder.value === 'ASC' ? 1 : -1;

    if (field === 'date') {
      return (new Date(b[field]) - new Date(a[field])) * order;
    }

    return (b[field] - a[field]) * order;
  });


  return result;
});

const totalPages = computed(() => Math.ceil(filteredArticles.value.length / pageSize.value));
const paginatedArticles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredArticles.value.slice(start, end);
});



const applyFilters = () => {
  currentPage.value = 1; // 重置到第一页
};

const resetFilters = () => {
  searchQuery.value = '';
  filterCategory.value = '';
  sortField.value = 'date';
  sortOrder.value = 'DESC';
  currentPage.value = 1;
};

const changePage = (page) => {
  currentPage.value = page;
};

const viewArticle = (id) => {
  previewArticle.value = articles.value.find(article => article.id === id);
  showPreview.value = true;
};

const editArticle = (id) => {
  console.log('编辑文章:', id);
};

const confirmDelete = (article) => {
  articleToDelete.value = article;
  showDeleteConfirm.value = true;
};

const deleteArticle = () => {
  articles.value = articles.value.filter(article => article.id !== articleToDelete.value.id);
  showDeleteConfirm.value = false;
  // console.log('删除文章:', articleToDelete.value.id);
  deleteArticleFlag(articleToDelete.value.id)
};
const deleteArticleFlag = async (articleId) => {
  try {
    const res = await deleteArticleApi(articleId);

    if (res.success) {
      console.log('文章删除成功');
      // 可选：更新前端数据、弹窗提示等
    } else {
      console.warn('删除失败:', res.message);
    }
  } catch (error) {
    console.error('请求出错:', error.message || error);
  }
};

const formatDate = (date) => {
  return new Date(date).toLocaleDateString();
};

const getCategoryColor = (category) => {
  const colors = {
    all: '#2a9d8f',       // 绿色 - 默认/全部
    cet4: '#38bdf8',      // 淡蓝 - CET4
    cet6: '#6366f1',      // 靛蓝 - CET6
    ielts: '#f472b6',     // 粉色 - IELTS
    toefl: '#fb923c',     // 橘黄 - TOEFL
    gre: '#10b981',       // 绿色 - GRE
    business: '#facc15',  // 金黄 - 商务
  };
  return colors[category] || '#94a3b8'; // 默认灰色 fallback
};


const loadPageData = async () => {
  try {
    const [articleArr] = await Promise.all([
      getForumArticles()
    ])

    if (articleArr.success) {
      // console.log("文章列表:", articleArr.articles);
      articles.value = handAllArticleArr(articleArr.articles)
    } else {
      if (!articleArr.success) ElMessage.error(articleArr.message)
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求数据失败')
  }
}
// 方法
const fetchArticles = () => {
  articles.value = mockArticles;
};
const handAllArticleArr = (articleArr) => {
  const afterHandArticleArr = articleArr.map(item => ({
    id: item.id,
    title: item.title,
    word: item.word,
    excerpt: item.excerpt,
    category: item.category,
    votes: item.votes,
    comments: item.comments,
    date: formatDate(item.date),
    user_id: item.user_id,
    content: item.content
  }));
  // console.log(afterHandArticleArr, ' afterHandArticleArr');
  return afterHandArticleArr;
};


// 初始化
onMounted(() => {
  // fetchArticles();
  loadPageData()
});
</script>

<style scoped>
.word-forum {
  --bg-color: #f8f9fa;
  --text-color: #333;
  --primary-color: #4361ee;
  --secondary-color: #6c757d;
  --border-color: #e1e4e8;
  --card-bg: #fff;
  --hover-bg: #f1f3f5;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  --danger-color: #dc3545;
  --warning-color: #ffc107;
  --success-color: #28a745;
  --info-color: #17a2b8;
}

.word-forum.dark {
  --bg-color: #1a1a1a;
  --text-color: #e0e0e0;
  --primary-color: #4895ef;
  --secondary-color: #8e8e8e;
  --border-color: #333;
  --card-bg: #2d2d2d;
  --hover-bg: #383838;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.admin-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 0 20px;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0;
  font-size: 24px;
  color: var(--primary-color);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.theme-toggle {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: var(--text-color);
  padding: 5px;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.theme-toggle:hover {
  background-color: var(--hover-bg);
}

.admin-name {
  font-weight: 500;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  display: flex;
  align-items: center;
  flex-grow: 1;
  max-width: 400px;
}

.search-box input {
  flex-grow: 1;
  padding: 10px 15px;
  border: 1px solid var(--border-color);
  border-radius: 4px 0 0 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
}

.search-btn {
  padding: 10px 15px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn:hover {
  opacity: 0.9;
}

.filters {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filters select {
  padding: 10px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
  cursor: pointer;
}

.refresh-btn {
  padding: 10px 15px;
  background-color: var(--secondary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.refresh-btn:hover {
  opacity: 0.9;
}

.table-container {
  background-color: var(--card-bg);
  border-radius: 8px;
  box-shadow: var(--shadow);
  overflow: hidden;
}

.articles-table {
  width: 100%;
  border-collapse: collapse;
}

.articles-table th,
.articles-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.articles-table th {
  background-color: var(--hover-bg);
  font-weight: 600;
}

.articles-table tr:hover {
  background-color: var(--hover-bg);
}

.title-cell {
  max-width: 200px;
}

.title-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.category-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.actions {
  display: flex;
  gap: 8px;
}

.view-btn,
.edit-btn,
.delete-btn {
  padding: 6px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
}

.view-btn {
  color: var(--primary-color);
}

.view-btn:hover {
  background-color: rgba(67, 97, 238, 0.1);
}

.edit-btn {
  color: var(--warning-color);
}

.edit-btn:hover {
  background-color: rgba(255, 193, 7, 0.1);
}

.delete-btn {
  color: var(--danger-color);
}

.delete-btn:hover {
  background-color: rgba(220, 53, 69, 0.1);
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  gap: 10px;
  align-items: center;
}

.pagination button,
.pagination span {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  background-color: var(--card-bg);
  color: var(--text-color);
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination span.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.page-info {
  margin-left: 15px;
  font-size: 14px;
  color: var(--secondary-color);
}

.no-data {
  text-align: center;
  padding: 20px;
  color: var(--secondary-color);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--card-bg);
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: var(--shadow);
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--secondary-color);
  padding: 5px;
}

.close-btn:hover {
  color: var(--text-color);
}

.modal-body {
  padding: 20px;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;
}

.meta-item {
  font-size: 14px;
  color: var(--secondary-color);
}

.article-excerpt,
.article-content {
  margin-bottom: 20px;
}

.article-excerpt h4,
.article-content h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
}

.article-excerpt p {
  margin: 0;
  line-height: 1.6;
}

.confirm-modal {
  background-color: var(--card-bg);
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: var(--shadow);
}

.confirm-header {
  padding: 15px 20px;
  border-bottom: 1px solid var(--border-color);
}

.confirm-header h3 {
  margin: 0;
  font-size: 18px;
}

.confirm-body {
  padding: 20px;
}

.confirm-footer {
  padding: 15px 20px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: var(--secondary-color);
  color: white;
  border: none;
}

.confirm-btn {
  background-color: var(--danger-color);
  color: white;
  border: none;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    max-width: 100%;
  }

  .filters {
    justify-content: space-between;
    width: 100%;
  }

  .articles-table {
    display: block;
    overflow-x: auto;
  }
}
</style>